using System;
using System.Web.Mvc;
using Autofac.Integration.Mvc;

namespace Limestone.MVC
{
    [ModelBinderType(typeof(FieldSetting))]
    public class AbstractFieldSettingBinder : DefaultModelBinder
    {
        // TODO this should ideally reside in the Limestone assembly but for some reason Autofac wont bind to it properly
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var fieldSettingTypeName = controllerContext.HttpContext.Request.Form[bindingContext.ModelName + ".Type"];

            var fieldSetting = FieldFactory.CreateFieldSetting(fieldSettingTypeName);

            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => fieldSetting,
                                                                                             fieldSetting.GetType());
            return fieldSetting;
        }
    }
}